<script setup lang="ts">
  import { reactive, ref, watch, PropType } from 'vue'
  import _ from 'lodash'
  import { ElMessage, FormInstance } from 'element-plus'
  import { changeNetwork } from '@/api/order'
  import { getNetworkEmpPageSelect, getNetworkSelect, networkTypePageSelect } from '@/api/network'
  import {
    NetowrkOptional,
    NetworkEmpOptional,
    NetworkTypeOptional,
  } from '@/components/pages/order/index/AssignNetwork/types'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'

  const props = defineProps({
    network: {
      type: String,
      required: true,
    },
    networkId: {
      type: String,
      required: true,
    },
    orderId: {
      type: String,
      required: true,
    },
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    address: Object as PropType<{
      province: string
      city: string
      area: string
      town: string
      address: string
    }>,
  })

  const emits = defineEmits<{
    (e: 'update-list'): void
    (e: 'update:modelValue', value: boolean): void
    (e: 'close'): void
  }>()

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService(['newNetwork'])

  // 表单
  const form = ref({
    networkEmpId: '',
    oldNetwork: props.network,
    newNetwork: '',
    remark: '',
  })

  // 弹窗的显示状态
  const visible = ref(false)

  // 表单校验规则
  const rules = reactive({
    newNetwork: [{ required: true, message: '请选择服务商！', trigger: ['blur', 'change'] }],
  })

  // 表单组件实例
  const formRef = ref<FormInstance>()

  // 保存加载
  const saveLoading = ref(false)

  /**
   * 保存事件
   */
  const onSave = () => {
    if (formRef.value) {
      formRef.value.validate((valid) => {
        if (valid) {
          const temp = {
            changeToNetworkEmpId: form.value.networkEmpId, //	改派的服务商人员ID
            changeToNetworkId: form.value.newNetwork, //改派的服务商ID
            currentNetworkId: props.networkId, //当前服务商ID
            remark: form.value.remark,
            workId: props.orderId,
          }
          saveLoading.value = true
          changeNetwork(temp).then((res) => {
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: res.data.success ? 'success' : 'error',
                duration: 3000,
              })
            if (res?.data.success) {
              emits('update-list')
              onCancel()
            }
            saveLoading.value = false
          })
        }
      })
    }
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    form.value.newNetwork = ''
    visible.value = false
    form.value.remark = ''
    form.value.networkEmpId = ''
    networkType.value = ''
    filterType.value = 3
    addr.value = {
      city: '',
      area: '',
      province: '',
      town: '',
    }
    resetFormValidateResult()
    emits('close')
    emits('update:modelValue', visible.value)
  }

  // 服务商选项
  const networkOptional = ref<Array<NetowrkOptional>>([])

  // 获取服务商选项加载
  const getNetworkOptionalLoading = ref(false)

  // 获取服务商选项请求参数
  const getNetworkOptionsParam = ref({
    area: '',
    city: '',
    limit: 0,
    name: '',
    page: 0,
    province: '',
    type: 0,
    typeId: null,
    areaType: 2,
  })

  /**
   * 获取服务商选项
   */
  const getNetworkPageSelectList = _.throttle((query: string) => {
    if (query === getNetworkOptionsParam.value.name) {
      return false
    }
    getNetworkOptionsParam.value.name = query
    getNetworkOptionsFn()
  }, 500)

  /**
   * 获取服务商下拉选项方法
   */
  const getNetworkOptionsFn = async () => {
    getNetworkOptionalLoading.value = true
    Object.assign(getNetworkOptionsParam.value, {
      area: [0, 1].includes(filterType.value) ? '' : addr.value.area,
      city: [0, 1].includes(filterType.value) ? '' : addr.value.city,
      limit: 0,
      page: 0,
      province: [0, 1].includes(filterType.value) ? '' : addr.value.province,
      type: filterType.value,
      typeId: [0, 2].includes(filterType.value) ? null : networkType.value,
    })
    if (getNetworkOptionsParam.value.typeId === '0') {
      getNetworkOptionsParam.value.typeId = ''
    }
    const res = await getNetworkSelect(getNetworkOptionsParam.value)
    networkOptional.value = res.data.success ? res.data.data.rows : []
    getNetworkOptionalLoading.value = false
  }

  // 分配人员选项
  const networkEmpOptional = ref<Array<NetworkEmpOptional>>([])

  // 获取分配人员选项加载
  const getNetworkEmpOptionalLoading = ref(false)

  // 获取分配人员选项请求参数
  const getNetworkEmpOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  /**
   * 获取分配人员选项
   */
  const getNetworkEmpPageSelectList = _.throttle((query: string) => {
    // 服务没有选择服务商就退出
    if (!form.value.newNetwork || getNetworkEmpOptionsParam.value.name === query) return
    getNetworkEmpOptionsParam.value.name = query
    getNetworkEmpOptionsFn()
  }, 500)

  /**
   * 获取分配人员下拉选项方法
   */
  // 判断是否是个人
  const isTeamType = ref(false)
  const getNetworkEmpOptionsFn = async () => {
    getNetworkEmpOptionalLoading.value = true
    const res = await getNetworkEmpPageSelect(
      getNetworkEmpOptionsParam.value,
      form.value.newNetwork,
    )
    networkEmpOptional.value = res.data.success ? res.data.data.rows : []
    let arr = networkOptional.value.filter((o) => o.id == form.value.newNetwork)
    isTeamType.value = false
    if (arr[0].teamType == 2) {
      form.value.networkEmpId = networkEmpOptional.value[0].id
      isTeamType.value = true
    }
    getNetworkEmpOptionalLoading.value = false
  }

  // 服务商分类
  const networkType = ref('0')

  // 服务商类型选项
  const networkTypeOptional = ref<Array<NetworkTypeOptional>>([])

  // 获取服务商类型选项
  const getNetworkTypeOptionalLoading = ref(false)

  // 获取服务商类型下拉选项请求参数
  const getNetworkTypeOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  /**
   * 获取服务商类型
   */
  const getNetworkTypeSelectList = _.throttle((query: string) => {
    if (getNetworkTypeOptionsParam.value.name === query) return
    getNetworkTypeOptionsParam.value.name = query
    getNetworkTypeOptionsFn()
  }, 500)

  /**
   * 获取服务商类型下拉选项方法
   */
  const getNetworkTypeOptionsFn = async () => {
    getNetworkTypeOptionalLoading.value = true
    const res = await networkTypePageSelect(getNetworkTypeOptionsParam.value)
    networkTypeOptional.value = res.data.success ? res.data.data.rows : []
    getNetworkTypeOptionalLoading.value = false
  }

  /**
   * 查询条件
   * 0 - 全部
   * 1 - 服务商分类
   * 2 - 按省市区
   */
  const filterType = ref(3)

  // 服务范围
  const addr = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 地址组件实例
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null)

  /**
   * 获取服务范围
   */
  const handleChangeAddress = () => {
    if (singleAddressRef.value) {
      Object.assign(addr.value, singleAddressRef.value.getSelectAddr())
      getNetworkOptionsFn()
    }
  }

  /**
   * 清空地址
   */
  const onClearAddress = () => {
    addr.value.province = ''
    addr.value.area = ''
    addr.value.city = ''
    addr.value.town = ''
    filterType.value = 3
    getNetworkOptionsFn()
  }

  /**
   * 查询条件更新事件
   * @param {number} val - 条件的值: 0.全部 1.按服务商分类 2.服务区域 3.客户地址
   */
  const onChangeCondition = async (val: 0 | 1 | 2 | 3) => {
    if (formRef.value) {
      formRef.value.resetFields()
      addr.value.province = ''
      addr.value.area = ''
      addr.value.city = ''
      addr.value.town = ''
    }
    if (val === 3 || val === 2) {
      if (props.address) {
        filterType.value = val
        addr.value.province = props.address.province
        addr.value.city = props.address.city
        addr.value.area = props.address.area
        addr.value.town = props.address.town
      }
    }
    if (val === 1) {
      await getNetworkTypeOptionsFn()
      networkType.value = '0'
    }
    await getNetworkOptionsFn()
  }
  /**
   * 显示弹窗事件
   */
  const onShowModal = async () => {
    visible.value = true
    networkEmpOptional.value = []
    getNetworkOptionsParam.value.areaType = 2
    if (props.address) {
      filterType.value = 3
      addr.value.province = props.address.province
      addr.value.city = props.address.city
      addr.value.area = props.address.area
      addr.value.town = props.address.town
    } else {
      await getNetworkTypeOptionsFn()
    }
    await getNetworkOptionsFn()
  }

  /**
   * 更新服务商事件
   */
  const onChangeNetwork = () => {
    form.value.networkEmpId = ''
    getNetworkEmpOptionsFn()
  }

  /**
   * 服务商分类选择事件
   */
  const handleChangeNetworkType = async () => {
    form.value.newNetwork = ''
    await getNetworkOptionsFn()
  }

  watch(
    () => props.modelValue,
    async (value) => {
      visible.value = value
      if (value) {
        networkEmpOptional.value = []
        getNetworkOptionsParam.value.areaType = 2
        if (props.address) {
          filterType.value = 3
          addr.value.province = props.address.province
          addr.value.city = props.address.city
          addr.value.area = props.address.area
          addr.value.town = props.address.town
        } else {
          await getNetworkTypeOptionsFn()
        }
        await getNetworkOptionsFn()
      }
    },
    { immediate: true },
  )
</script>

<template>
  <div>
    <span @click="onShowModal">
      <slot></slot>
    </span>

    <HModal title="改派服务商" v-model="visible" @close="onCancel" width="auto">
      <div v-loading="saveLoading">
        <div class="alert_container">
          <el-alert
            class="alert"
            show-icon
            :closable="false"
            title="改派后，该工单不再属于原服务商"
            type="warning"
          />
        </div>
        <el-form
          label-width="82"
          ref="formRef"
          :rules="rules"
          :model="form"
          class="modal_form_content"
          @validate="handleFormValidate"
        >
          <!--当前服务商-->
          <el-form-item label="当前服务商" class="form_input_item">
            <el-input disabled :value="form.oldNetwork" />
          </el-form-item>

          <!-- 查询条件 -->
          <el-form-item label="查询条件" class="form_select_item">
            <el-select
              placeholder="请选择查询条件"
              filterable
              v-model="filterType"
              @blur.stop="() => {}"
              @change="onChangeCondition"
            >
              <el-option :value="0" label="全部" />
              <el-option :value="1" label="按服务商分类" />
              <el-option :value="2" label="服务区域" />
              <el-option :value="3" label="客户地址" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="filterType == 2 || filterType == 3"
            label="地址匹配"
            class="form_select_item"
          >
            <el-select
              placeholder="请选择查询条件"
              v-model="getNetworkOptionsParam.areaType"
              @blur.stop="() => {}"
              @change="onChangeCondition(filterType)"
            >
              <el-option :value="1" label="全地址匹配" />
              <el-option :value="2" label="仅匹配省、市" />
            </el-select>
          </el-form-item>
          <!-- 服务范围 -->
          <el-form-item
            :label="filterType === 3 ? '客户地址' : '服务区域'"
            v-if="filterType === 3 || filterType === 2"
            class="form_select_item"
          >
            <SingleAddress
              :address="addr"
              ref="singleAddressRef"
              @value-change="handleChangeAddress"
              checkStrictly
              @clear="onClearAddress"
            />
          </el-form-item>

          <!-- 服务商分类 -->
          <el-form-item label="服务商分类" v-if="filterType === 1" class="form_select_item">
            <el-select
              placeholder="服务商分类"
              filterable
              v-model="networkType"
              :filter-method="getNetworkTypeSelectList"
              :loading="getNetworkTypeOptionalLoading"
              remote-show-suffix
              @change="handleChangeNetworkType"
            >
              <el-option value="0" label="全部" />
              <el-option
                v-for="item in networkTypeOptional"
                :key="item.name"
                :disabled="networkId === item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>

          <!-- 分配服务商 -->
          <el-form-item
            label="分配服务商"
            required
            prop="newNetwork"
            class="form_select_item"
            :class="{ error_form_item: !formValidateResult['newNetwork'] }"
          >
            <el-select
              placeholder="分配服务商"
              filterable
              v-model="form.newNetwork"
              :filter-method="getNetworkPageSelectList"
              :loading="getNetworkOptionalLoading"
              remote-show-suffix
              @change="onChangeNetwork"
            >
              <el-option
                v-for="(item, index) in networkOptional"
                :key="index"
                :disabled="networkId === item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>

          <!-- 分配人员 -->
          <el-form-item label="分配人员" v-if="!isTeamType" class="form_select_item">
            <el-select
              v-model="form.networkEmpId"
              placeholder="分配人员"
              filterable
              :filter-method="getNetworkEmpPageSelectList"
              :loading="getNetworkEmpOptionalLoading"
              remote-show-suffix
              clearable
            >
              <el-option
                v-for="item in networkEmpOptional"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!--备注-->
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              maxlength="200"
              placeholder="请输入备注"
              show-word-limit
              type="textarea"
              resize="both"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSave" :loading="saveLoading">保存</HButton>
        <HButton isModal @click="onCancel" :loading="saveLoading">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './UpdateNetwork.scss';
</style>
